﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace ShopPowerTemplate.Infrastructure
{
    public class LiveIDService
    {
        public async Task<LiveConnectUserProfile> GetUserProfileFromLiveConnect(string liveConnectAccessCode)
        {
            LiveConnectUserProfile profile = null;

            string requestUrl = "https://apis.live.net/v5.0/me?access_token=" + liveConnectAccessCode;

            try
            {
                string responseBody = await FetchGetAsync(requestUrl);
                profile = JsonConvert.DeserializeObject<LiveConnectUserProfile>(responseBody);
            }
            catch (Exception ex)
            {
                throw new AuthenticationException(ex);
            }

            return profile;
        }

        public static async Task<string> FetchGetAsync(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";

            using (var response = (HttpWebResponse) await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null))
            using (var responseStream = response.GetResponseStream())
            {
                var output = new MemoryStream();
                await responseStream.CopyToAsync(output);
                var data = output.ToArray();
                return Encoding.UTF8.GetString(data, 0, data.Length);
            }
        }
    }
}
